<template>
  <div class="rollbackTop" :class="{show}" @click="backtop()">
    <i class="iconfont icon-backtop"></i>
    <p>回到顶部</p>
</div>
</template>

<script>
import { onMounted, ref } from 'vue'
export default {
  name: 'AppBacktop',
  setup () {
    const show = ref(false)
    onMounted(() => {
      // 组件挂载后执行
      window.onscroll = () => {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
        if (scrollTop > 1000) {
          show.value = true
        } else {
          show.value = false
        }
      }
    })
    const backtop = () => {
      var timer = null
      timer = setInterval(() => {
        // 获取当前页面距离顶部的距离
        var osTop = document.documentElement.scrollTop || document.body.scrollTop
        // 计算每次向上移动的距离，用负的滚动距离除以5，因为滚动的距离是一个正数，向上移动就是一个减法
        var isSpeed = Math.floor(-osTop / 5)
        // 用当前距离加上计算出的距离，然后赋值给当前距离，就可以达到向上移动的效果
        document.documentElement.scrollTop = document.body.scrollTop = osTop + isSpeed
        // 当前距离为0时就表示到达顶部，此时移除定时器
        if (osTop === 0) {
          clearInterval(timer)
        }
      }, 30)
    }
    return { show, backtop }
  }
}
</script>

<style lang="less" scoped>
.rollbackTop {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate3d(640px,-50%,0);
  width: 80px;
  height: 80px;
  border-radius: 4px;
  border: 1px solid #e4e4e4;
  background: #fff;
  box-shadow: 0 0 2px #e4e4e4;
  text-align: center;
  padding-top: 10px;
  color: #999;
  opacity: 0;
  transition: opacity .6s;
  .iconfont {
    font-size: 20px;
  }
  p {
    line-height: 32px;
    font-size: 12px;
  }
  &:hover {
    cursor: pointer;
    color: @xtxColor;
  }
  &.show {
    opacity: 1;
  }
}
</style>
